using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace StarSkipGame
{
    /// <summary>
    /// 高分记录结构
    /// </summary>
    public class HighScoreRecord
    {
        public string PlayerName { get; set; }
        public float Score { get; set; } // 生存时间（秒）
        public int TotalEnemies { get; set; } // 总敌人数量
        public DateTime Date { get; set; }
        public string GameMode { get; set; }

        public HighScoreRecord()
        {
            PlayerName = "Unknown";
            Score = 0;
            TotalEnemies = 0;
            Date = DateTime.Now;
            GameMode = "Classic";
        }

        public HighScoreRecord(string playerName, float score, int totalEnemies, string gameMode)
        {
            PlayerName = playerName;
            Score = score;
            TotalEnemies = totalEnemies;
            Date = DateTime.Now;
            GameMode = gameMode;
        }

        public override string ToString()
        {
            return string.Format("{0} - {1:F1}秒 ({2}) - 敌人:{3} - {4}", 
                PlayerName, Score, GameMode, TotalEnemies, Date.ToString("yyyy-MM-dd HH:mm"));
        }
    }

    /// <summary>
    /// 高分管理器类
    /// </summary>
    public class HighScoreManager
    {
        private const string HIGH_SCORE_FILE = "highscores.txt";
        private const int MAX_HIGH_SCORES = 10;
        private List<HighScoreRecord> highScores;

        public List<HighScoreRecord> HighScores
        {
            get { return highScores; }
        }

        public HighScoreManager()
        {
            highScores = new List<HighScoreRecord>();
            LoadHighScores();
        }

        /// <summary>
        /// 检查是否为新的高分
        /// </summary>
        /// <param name="score">当前分数</param>
        /// <param name="gameMode">游戏模式</param>
        /// <returns>是否为新高分</returns>
        public bool IsNewHighScore(float score, string gameMode)
        {
            var modeScores = highScores.Where(hs => hs.GameMode == gameMode).ToList();
            
            if (modeScores.Count < MAX_HIGH_SCORES)
                return true;

            return modeScores.Any(hs => hs.Score < score);
        }

        /// <summary>
        /// 添加新的高分记录
        /// </summary>
        /// <param name="playerName">玩家名称</param>
        /// <param name="score">生存时间（秒）</param>
        /// <param name="totalEnemies">总敌人数量</param>
        /// <param name="gameMode">游戏模式</param>
        /// <returns>是否成功添加</returns>
        public bool AddHighScore(string playerName, float score, int totalEnemies, string gameMode)
        {
            if (string.IsNullOrEmpty(playerName))
                playerName = "Unknown";

            var newRecord = new HighScoreRecord(playerName, score, totalEnemies, gameMode);
            
            // 添加新记录
            highScores.Add(newRecord);
            
            // 按游戏模式和生存时间排序（时间越长排名越高）
            highScores = highScores
                .GroupBy(hs => hs.GameMode)
                .SelectMany(g => g.OrderByDescending(hs => hs.Score).Take(MAX_HIGH_SCORES))
                .ToList();

            // 保存到文件
            SaveHighScores();
            
            return true;
        }

        /// <summary>
        /// 获取指定模式的高分记录
        /// </summary>
        /// <param name="gameMode">游戏模式</param>
        /// <returns>高分记录列表</returns>
        public List<HighScoreRecord> GetHighScoresForMode(string gameMode)
        {
            return highScores
                .Where(hs => hs.GameMode == gameMode)
                .OrderByDescending(hs => hs.Score)
                .Take(MAX_HIGH_SCORES)
                .ToList();
        }

        /// <summary>
        /// 获取所有高分记录
        /// </summary>
        /// <returns>所有高分记录</returns>
        public List<HighScoreRecord> GetAllHighScores()
        {
            return highScores.OrderByDescending(hs => hs.Score).ToList();
        }

        /// <summary>
        /// 获取最高分
        /// </summary>
        /// <param name="gameMode">游戏模式（可选）</param>
        /// <returns>最高分记录</returns>
        public HighScoreRecord GetTopScore(string gameMode = null)
        {
            var scores = gameMode != null 
                ? highScores.Where(hs => hs.GameMode == gameMode)
                : highScores;
                
            return scores.OrderByDescending(hs => hs.Score).FirstOrDefault();
        }

        /// <summary>
        /// 清除所有高分记录
        /// </summary>
        public void ClearAllHighScores()
        {
            highScores.Clear();
            SaveHighScores();
        }

        /// <summary>
        /// 清除指定模式的高分记录
        /// </summary>
        /// <param name="gameMode">游戏模式</param>
        public void ClearHighScoresForMode(string gameMode)
        {
            highScores.RemoveAll(hs => hs.GameMode == gameMode);
            SaveHighScores();
        }

        /// <summary>
        /// 从文件加载高分记录
        /// </summary>
        private void LoadHighScores()
        {
            try
            {
                if (!File.Exists(HIGH_SCORE_FILE))
                    return;

                highScores.Clear();
                string[] lines = File.ReadAllLines(HIGH_SCORE_FILE, Encoding.UTF8);

                foreach (string line in lines)
                {
                    if (string.IsNullOrWhiteSpace(line))
                        continue;

                    try
                    {
                        string[] parts = line.Split('|');
                        if (parts.Length >= 5)
                        {
                            var record = new HighScoreRecord
                            {
                                PlayerName = parts[0],
                                Score = float.Parse(parts[1]),
                                TotalEnemies = int.Parse(parts[2]),
                                GameMode = parts[3],
                                Date = DateTime.Parse(parts[4])
                            };
                            highScores.Add(record);
                        }
                        else if (parts.Length >= 4) // 兼容旧格式
                        {
                            var record = new HighScoreRecord
                            {
                                PlayerName = parts[0],
                                Score = float.Parse(parts[1]),
                                TotalEnemies = 0, // 旧记录默认为0
                                GameMode = parts[2],
                                Date = DateTime.Parse(parts[3])
                            };
                            highScores.Add(record);
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("解析高分记录失败: " + ex.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("加载高分记录失败: " + ex.Message);
            }
        }

        /// <summary>
        /// 保存高分记录到文件
        /// </summary>
        private void SaveHighScores()
        {
            try
            {
                var lines = highScores.Select(hs => 
                    string.Format("{0}|{1}|{2}|{3}|{4}", 
                        hs.PlayerName, 
                        hs.Score.ToString("F1"), 
                        hs.TotalEnemies.ToString(), 
                        hs.GameMode, 
                        hs.Date.ToString("yyyy-MM-dd HH:mm:ss")));

                File.WriteAllLines(HIGH_SCORE_FILE, lines, Encoding.UTF8);
            }
            catch (Exception ex)
            {
                Console.WriteLine("保存高分记录失败: " + ex.Message);
            }
        }
    }
} 